﻿// -------------------------------------------------------------------------
//    @FileName         :    NFCityNpcUtil.cpp
//    @Author           :    Gao.Yi
//    @Date             :    2025-09-29
//    @Email			:    445267987@qq.com
//    @Module           :    NFCityNpcUtil
//    @Desc             :
//
// -------------------------------------------------------------------------

#include "NFCityNpcUtil.h"

#include "NFCityMapInst.h"
#include "NFCityMapUtil.h"
#include "NFCityNpc.h"
#include "NFCityNpcMgr.h"
#include "DescStore/FunctionNpcDesc.h"

NFCityNpc* NFCityNpcUtil::CreateNpc(int iMapInstID, int iNpcID, const Proto_Vector3& oPos, int iDirection, int iDuration)
{
    LOG_DEBUG(iNpcID, "--create npc:{} mapInstID:{} pos:[x:{}, y:{}, z:{}] iDrection:{} iDuration:{}", iNpcID, iMapInstID, oPos.x, oPos.y, oPos.z, iDirection, iDuration);

    auto pNpcDesc = FunctionNpcDesc::Instance()->GetDesc(iNpcID);
    CHECK_NULL_RE_NULL(iNpcID, pNpcDesc, "invalid npc id:{}", iNpcID);

    auto pMapInst = NFCityMapInst::GetObjByGlobalId(iMapInstID);
    CHECK_NULL_RE_NULL(iNpcID, pMapInst, "invalid mapinst id:{}", iMapInstID);

    NFCityNpc* pNpc = NFCityNpc::CreateObj();
    CHECK_NULL_RE_NULL(0, pNpc, "create npc obj failed!");

    pNpc->Init(iNpcID, iDuration);

    int iRetCode = NFCityMapUtil::EnterMap(pNpc, pMapInst, oPos, iDirection);
    if (iRetCode)
    {
        RemoveNpc(pNpc);
        return nullptr;
    }

    if (pNpcDesc->function.size() > 0)
    {
        if (pNpcDesc->function[0].type == proto_ff::EN_FUNCTION_NPC_TYPE_GOLD_BOX || pNpcDesc->function[0].type == proto_ff::EN_FUNCTION_NPC_TYPE_SILVER_BOX)
        {
            //NotifyFieldBoxCreate(pNpc->GetGlobalID(), pNpcDesc->function[0].type, pMapInst->GetMapDescID());
        }
    }

    return pNpc;
}

int NFCityNpcUtil::RemoveNpc(NFCityNpc* pNpc)
{
    CHECK_NULL(0, pNpc);

    LOG_DEBUG(0, "remove npc obj id:{}, desc id:", pNpc->GetGlobalId(), pNpc->GetNpcID());

    int iTransNpcId = pNpc->GetLevelExt()->GetTransNpcObjId();
    if (iTransNpcId > 0)
    {
        NFCityNpc* pTransNpc = NFCityNpc::GetObjByGlobalId(iTransNpcId);
        if (pTransNpc)
        {
            pTransNpc->SetRemove();
        }
    }

    ReduceSpawnNpcCnt(pNpc);

    NFCityMapUtil::LeaveMap(pNpc);

    NFCityNpc::DestroyObj(pNpc);

    return 0;
}

int NFCityNpcUtil::OnNpcSpawnEvent(int iEventId, int& iNum, int aiSpawnId[])
{
    return 0;
}

int NFCityNpcUtil::DoSpawnNpc(int iSpawnId)
{
    return 0;
}

int NFCityNpcUtil::ReduceSpawnNpcCnt(NFCityNpc* pNpc)
{
    CHECK_NULL(0, pNpc);

    if (pNpc->IsDynamicNpc())
    {
        NFCityMapInst* pMapInst = NFCityMapInst::GetObjByGlobalId(pNpc->GetMapInstId());
        CHECK_NULL(0, pMapInst);

        NFCityNpcMgr* pNpcMgr = pMapInst->GetNpcMgr();
        CHECK_NULL(0, pNpcMgr);
        pNpcMgr->OnRemoveNpc(pNpc);
    }

    return 0;
}
